package edu.arhs.team1100.gamename.forms;

import edu.arhs.team1100.gamename.handlers.EventHandler;
import edu.arhs.team1100.gamename.handlers.TeamEventMatchHandler;
import edu.arhs.team1100.gamename.objects.Match;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Eddie
 */
public class MatchViewPanel extends javax.swing.JPanel {

    /**
     * Creates new form TeamViewPanel
     *
     * @param matchesToView
     */
    public MatchViewPanel(List<Match> matchesToView) {
        initComponents();
        loadTeams(matchesToView);
        initRightMouseClick();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        editPopupMenu = new javax.swing.JPopupMenu();
        editMenuItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();
        teamMatchesTab = new javax.swing.JScrollPane();
        teamMatchTable = new javax.swing.JTable();

        editMenuItem.setText("Edit");
        editMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuItemActionPerformed(evt);
            }
        });
        editPopupMenu.add(editMenuItem);

        deleteMenuItem.setText("Delete");
        deleteMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMenuItemActionPerformed(evt);
            }
        });
        editPopupMenu.add(deleteMenuItem);

        teamMatchTable.setBorder(javax.swing.BorderFactory.createTitledBorder("Yellow"));
        teamMatchTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Match Number", "Team Number", "Event Name", "null"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        teamMatchTable.getTableHeader().setReorderingAllowed(false);
        teamMatchesTab.setViewportView(teamMatchTable);
        if (teamMatchTable.getColumnModel().getColumnCount() > 0) {
            teamMatchTable.getColumnModel().getColumn(3).setMinWidth(0);
            teamMatchTable.getColumnModel().getColumn(3).setPreferredWidth(0);
            teamMatchTable.getColumnModel().getColumn(3).setMaxWidth(0);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(teamMatchesTab, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(teamMatchesTab, javax.swing.GroupLayout.DEFAULT_SIZE, 703, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void editMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuItemActionPerformed
        DefaultTableModel model = (DefaultTableModel) teamMatchTable.getModel();
        MatchPanel matchPanel = new MatchPanel(getSelectedMatch());
        int eventResult = JOptionPane.showConfirmDialog(this, matchPanel, "Edit Match", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

        if (eventResult == JOptionPane.OK_OPTION) {
            Match updatedMatch = matchPanel.getMatch();
            TeamEventMatchHandler.updateMatch(updatedMatch);
            int position = teamMatchTable.getSelectedRow();
            model.removeRow(position);
            model.insertRow(position, new Object[]{updatedMatch.getMatchNumber(), updatedMatch.getTeamNumber(), EventHandler.getEventFromId(updatedMatch.getEventID()).getName(), updatedMatch});
        }
    }//GEN-LAST:event_editMenuItemActionPerformed

    private void deleteMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMenuItemActionPerformed
        DefaultTableModel model = (DefaultTableModel) teamMatchTable.getModel();
        TeamEventMatchHandler.deleteMatch(getSelectedMatch());
        model.removeRow(teamMatchTable.getSelectedRow());
    }//GEN-LAST:event_deleteMenuItemActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JMenuItem editMenuItem;
    private javax.swing.JPopupMenu editPopupMenu;
    private javax.swing.JTable teamMatchTable;
    private javax.swing.JScrollPane teamMatchesTab;
    // End of variables declaration//GEN-END:variables


    private void loadTeams(List<Match> matchesToView){
        DefaultTableModel model = (DefaultTableModel) teamMatchTable.getModel();
        for (Match match : matchesToView) {
            model.addRow(new Object[]{match.getMatchNumber(), match.getTeamNumber(), EventHandler.getEventFromId(match.getEventID()).getName(), match});
        }
    }

    public Match getSelectedMatch() {
        if (teamMatchTable.getSelectedRow() != -1) {
            return (Match) teamMatchTable.getValueAt(teamMatchTable.getSelectedRow(), 3);
        } else {
            return null;
        }
    }

    private void initRightMouseClick() {
        teamMatchTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                int r = teamMatchTable.rowAtPoint(e.getPoint());
                if (r >= 0 && r < teamMatchTable.getRowCount()) {
                    teamMatchTable.setRowSelectionInterval(r, r);
                } else {
                    teamMatchTable.clearSelection();
                }

                int rowindex = teamMatchTable.getSelectedRow();
                if (rowindex < 0) {
                    return;
                }
                if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
                    editPopupMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }

            @Override
            public void mousePressed(MouseEvent me) {
                if (me.getClickCount() == 2) {
                    editMenuItemActionPerformed(null);
                }
            }
        });
    }

}
